<script setup>
import { useUserStore } from '@/stores/user';
import { useXmRouter } from '@/stores/XmRouter';
import { useHeadersStore } from '@/stores/headers';

const dev = import.meta.env.MODE === 'development';

const user = useUserStore();
const headers = useHeadersStore();
const router = useRouter();
const xmRouter = useXmRouter();

const transitionName = ref('');

router.beforeEach((to) => {
  if (!user.isLogin && to.path !== '/login') {
    // router.replace('/login');
  }
  const { name } = to;
  xmRouter.push(name);
  if (to.meta) {
    const { title = '' } = to.meta;
    document.title = title;
  }
});

onMounted(() => {
  // 读取缓存票据，解决刷新重复登录
  if (localStorage.getItem('x-token')) {
    const token = localStorage.getItem('x-token') || '';
    user.xToken = token;
    headers.set('x-token', token);
    user.loginName = localStorage.getItem('loginName') || '';
    const userDataStr = localStorage.getItem('userData');
    if (userDataStr) {
      const userData = JSON.parse(userDataStr);
      user.userData = userData;
      user.username = userData.userName;
    }
    user.loginStatus = true;
  }
});
</script>
<template>
  <section class="vue-app">
    <RouterView v-slot="{ Component, route }">
      <Transition mode="out-in" :name="transitionName">
        <KeepAlive :include="xmRouter['keepAlive']">
          <component :is="Component" v-if="!dev" :key="route.path" />
        </KeepAlive>
      </Transition>
      <Transition mode="out-in" :name="transitionName">
        <component :is="Component" v-if="dev" :key="route.path" />
      </Transition>
    </RouterView>
  </section>
</template>

<style lang="stylus">
.vue-app

  .slide-fade-enter-active
    transition all 0.3s ease-out

  .slide-fade-enter-from
    opacity 0
    transform translateX(100vw)

  .slide-fade-leave-to
    opacity 0
    transform translateX(100vw)
</style>
